package gat.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class AddressUtil {

    public static String getIpAddress (HttpServletRequest request) {
        String ip = request.getHeader("X-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getAddress(String ip) {
        try {
            String url = String.format("http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true");
            String str = HttpUtil.get(url);
            System.out.println(str);
            if (!StrUtil.hasBlank(str)) {
                String substring = str.substring(str.indexOf("{"), str.indexOf("}") + 1);
                System.out.println(substring);
                JSONObject jsonObject = JSONUtil.parseObj(substring);
                String province = jsonObject.getStr("pro");
                String city = jsonObject.getStr("city");
                return province + " " + city;
            }
            return null;
        } catch (Exception ex) {
            log.error("获取地址异常");
        }
        return "";
    }

}
